package handler;

import entity.AdminDO;
import entity.StudentLoginDO;
import service.impl.AdminServiceImpI;
import service.impl.StudentLoginServiceImpI;
import view.LoginStudentView;
import view.LoginView;
import view.MainCourseView;
import view.StudentMainView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class LoginStudentHandler extends KeyAdapter implements ActionListener {
    private LoginStudentView loginStudentView;

    public LoginStudentHandler(LoginStudentView loginStudentView) {
        this.loginStudentView = loginStudentView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("重置".equals(text)) {
            loginStudentView.getUserTxt().setText("");
            loginStudentView.getPwdField().setText("");
        } else if ("登录".equals(text)) {
            login();
        }
    }


    private void login() {
        //得到用户名
        String user = loginStudentView.getUserTxt().getText();
        //System.out.println(user+"++");
        //得到密码
        char[] chars = loginStudentView.getPwdField().getPassword();

        if (user == null || "".equals(user.trim()) || chars == null) {
            JOptionPane.showMessageDialog(loginStudentView, "用户名密码必填");
            return;
        }
        String pwd = new String(chars);
        //System.out.println(user + ":" + pwd );

        //查询db
        StudentLoginServiceImpI serviceImpI = new StudentLoginServiceImpI();
        StudentLoginDO studentLoginDO = new StudentLoginDO();
        //System.out.println(user+"1234");
        studentLoginDO.setUsername(user);
        studentLoginDO.setPwd(pwd);
        boolean flag = serviceImpI.validateStudent(studentLoginDO);
        if (flag) {
            //验证之后跳转主界面
            //new MainView();
//            new MainCourseView();
//            new LoginStudentView();
            System.out.println("跳转学生端");
            new StudentMainView();
            loginStudentView.dispose();
        } else {
            JOptionPane.showMessageDialog(loginStudentView, "用户名密码错误");
        }
    }
//0626


    @Override
    public void keyPressed(KeyEvent e) {
        //super.keyPressed(e);
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            login();
        }
    }
}
